package com.abe.libcore.base.permission

import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.text.TextUtils
import com.yanzhenjie.permission.Action
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.Rationale
import com.yanzhenjie.permission.RequestExecutor
import com.yanzhenjie.permission.runtime.Permission
import com.yanzhenjie.permission.runtime.PermissionRequest
import java.io.File

object PermissionUtils {
    //回调
    interface PermissionCallback {
        fun onSuccess()
    }

    /**
     * 安装APK权限
     */
    fun installApk(context: Context?, fileName: String) {
        if (context == null || TextUtils.isEmpty(fileName)) return
        val file = File(fileName)
        installApk(context, file)
    }

    /**
     * 安装APK权限
     */
    fun installApk(context: Context?, file: File) {
        if (!file.exists()) return
        AndPermission.with(context)
                .install()
                .file(file)
                .start()
    }


    fun request(context: Context?, callback: PermissionCallback, vararg permissions: String) {
        if (AndPermission.hasPermissions(context, permissions)) {
            callback.onSuccess()
            return
        }
        AndPermission.with(context)
                .runtime()
                .permission(permissions)
                .onGranted(object : Action<List<String>> {
                    override fun onAction(data: List<String>?) {
                        callback.onSuccess()
                    }
                })
                .onDenied(createDeniedAction(context, permissions.toList()))
                .rationale(createRationale())
                .start()
    }


    fun createRequest(context: Context?, action: Action<List<String>>, vararg permissions: String): PermissionRequest {
        return AndPermission.with(context)
                .runtime()
                .permission(permissions)
                .onGranted(action)
                .onDenied(createDeniedAction(context, permissions.toList()))
                .rationale(createRationale())
    }

    private fun createDeniedAction(context: Context?, permissions: List<String>): Action<List<String>> {
        return NormalAction(context, permissions)
    }

    class NormalAction(var context: Context?, private var permissions: List<String>) : Action<List<String>> {
        override fun onAction(data: List<String>?) {
            if (AndPermission.hasPermissions(context, permissions.toTypedArray())) {
                //二次检测，防止申请权限成功后依然报无权限
                return
            }
            if (AndPermission.hasAlwaysDeniedPermission(context, permissions)) {
                permissionFail(context, data)
            }
        }
    }

    fun permissionFail(context: Context?, data: List<String>?) {
        if (data == null)
            return
        val ppData: List<String> = checkPermissions(data)
        val builder = StringBuilder()
        for (i in ppData.indices) {
            builder.append(ppData.get(i)).append("\n")
        }
        builder.append("您拒绝了我们以上必要的一些权限，请在设置中授权！")
        val dialog = AlertDialog.Builder(context)
                .setTitle("提示")
                .setMessage(builder.toString())
                .setNegativeButton("取消", object : DialogInterface.OnClickListener {
                    override fun onClick(dialog: DialogInterface?, which: Int) {
                        dialog?.dismiss()
                    }
                })
                .setPositiveButton("确定", object : DialogInterface.OnClickListener {
                    override fun onClick(dialog: DialogInterface?, which: Int) {
                        dialog!!.dismiss()
                        // NormalUtils.getAppDetailSettingIntent(context)
                        // 这里使用一个Dialog展示没有这些权限应用程序无法继续运行，询问用户是否去设置中授权。
                        AndPermission.with(context).runtime().setting().start(10010)
                    }
                }).create()
        dialog.show()
    }

    private fun checkPermissions(permissions: List<String>?): List<String> {
        val ppList: ArrayList<String> = ArrayList()
        if (permissions == null)
            return ppList
        val ppPermissions: Array<String> = arrayOf(
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE, Permission.READ_CALENDAR,
                Permission.WRITE_CALENDAR, Permission.CAMERA,
                Permission.READ_CONTACTS, Permission.WRITE_CONTACTS,
                Permission.GET_ACCOUNTS, Permission.ACCESS_FINE_LOCATION,
                Permission.ACCESS_COARSE_LOCATION, Permission.RECORD_AUDIO,
                Permission.READ_PHONE_STATE, Permission.CALL_PHONE,
                Permission.READ_CALL_LOG, Permission.WRITE_CALL_LOG,
                Permission.ADD_VOICEMAIL, Permission.USE_SIP,
                Permission.PROCESS_OUTGOING_CALLS, Permission.BODY_SENSORS,
                Permission.SEND_SMS, Permission.READ_SMS,
                Permission.RECEIVE_SMS, Permission.RECEIVE_WAP_PUSH,
                Permission.RECEIVE_MMS
        )
        val ppNames: Array<String> = arrayOf(
                "允许程序写入外部存储", "允许程序读取外部存储", "允许程序读取用户的日程信息",
                "写入日程", "打开相机", "读取联系人", "修改联系人", "访问手机账户", "精确定位", "定位", "录音",
                "读写手机状态", "拨打电话", "读取通话记录", "修改通话记录", "添加语音邮件", "视频服务",
                "允许应用程序监听、控制、取消呼出电话", "传感器", "发短信", "读短信", "接收短信",
                "接收WAP_PUSH", "接收彩信"
        )

        permissions.indices.forEach { i ->
            for (j in ppPermissions.indices) {
                if (permissions[i] == ppPermissions[j]) {
                    ppList.add(ppNames[j])
                }
            }
        }
        return ppList
    }

    private fun createRationale(): Rationale<List<String>> {
        return object : Rationale<List<String>> {
            override fun showRationale(context: Context?, data: List<String>?, executor: RequestExecutor?) {
                val ppData = checkPermissions(data)
                val builder = StringBuilder()
                for (i in ppData.indices) {
                    builder.append(ppData[i]).append("\n")
                }
                builder.append("您拒绝了我们以上必要的一些权限，请在设置中授权！")
                val dialog = AlertDialog.Builder(context)
                        .setTitle("提示")
                        .setMessage(builder.toString())
                        .setNegativeButton("取消", object : DialogInterface.OnClickListener {
                            override fun onClick(dialog: DialogInterface?, which: Int) {
                                dialog?.dismiss()
                                executor?.cancel()
                            }
                        })
                        .setPositiveButton("确定", object : DialogInterface.OnClickListener {
                            override fun onClick(dialog: DialogInterface?, which: Int) {
                                dialog?.dismiss()
                                executor?.execute()
                            }
                        }).create()
                dialog.show()
            }
        }
    }
}